package com.maple.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maple.admin.common.util.AjaxJson;
import com.maple.admin.domain.entity.SysUser;
import com.maple.admin.mapper.SysUserMapper;
import com.maple.admin.service.SysUserService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * (SysUser)表服务实现类
 *
 * @author SouthMaple
 * @since 2021-04-24 21:23:34
 */
@Service("saAdminService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    /**
     * admin登录
     *
     * @param username 账号
     * @param password 密码
     * @return 登录信息
     */
    @Override
    public AjaxJson login(String username, String password) {
        SysUser user = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username).eq(SysUser::getPw, password));

        // 验证账户是否存在
        if (user != null) {
            StpUtil.setLoginId(user.getId());
            String token = StpUtil.getTokenValue();
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return AjaxJson.getSuccess("登录成功!", map);
        }
        return AjaxJson.getError("账号或密码错误!");
    }

    /**
     * 根据token获取用户信息
     *
     * @param token 令牌
     * @return 用户信息
     */
    @Override
    public AjaxJson getInfo(String token) {
        Object loginId = StpUtil.getLoginIdByToken(token);
        SysUser user = baseMapper.selectById((Serializable) loginId);

        // 校验token
        if (user != null) {
            return AjaxJson.getSuccessData(user);
        }
        return AjaxJson.getError("token无效!");
    }

    /**
     * 退出登录
     *
     * @return 是否退出成功
     */
    @Override
    public AjaxJson logout() {
        StpUtil.logout();
        return AjaxJson.getSuccess("登出成功!");
    }
}

